const express = require('express');
const router = express.Router();
const dbConfig = require('../db.js')
const mysql = require('mysql');
const sql = require('../sql.js')

const multiparty = require('multiparty');

var connection = mysql.createConnection(dbConfig)
connection.connect();

router.use('/addCar',(req,res,next)=>{
	let form = new multiparty.Form();
	form.uploadDir = "upload";
	form.parse(req,(err,fields,files)=>{
		let license_num = fields.license_num[0];
		let type = fields.type[0];
		let brand = fields.brand[0];
		let path = files.file[0].path.split('\\')[1];
		
		let car = [license_num,type,brand,path]
		connection.query(sql.car.addCar,car,(err,result,fields)=>{
			
			if(err){
				console.log(err)
				res.sendStatus(500)
			}
			else{
				res.status(200).send('ok');
			}
		})	
	})
})

router.use('/queryCarNum',(req,res,next)=>{
	let num = req.body.num;
	connection.query(sql.car.queryCarNum,num,(err,result,fields)=>{
		if(err){
			console.log(err)
			res.sendStatus(500)
		}
		if(result.length == 0  ){
			res.send('nohas')
		}else{
			res.send('has')
		}
	})
})

router.use('/getUserName',(req,res,next)=>{
	let car_id = req.query.id;
	connection.query(sql.info.getUserName,car_id,(err,result,fields)=>{
		if(err){
			console.log(err)
			res.sendStatus(500)
		}
		res.send(result)
	})
})
// 改变车辆的状态
router.use('/chageCarState',(req,res,next)=>{
	let car_id = req.query.id;
	let state = req.query.state
	connection.query(sql.car.chageCarState,[state,car_id],(err,result,fields)=>{
		if(err){
			console.log(err)
			res.sendStatus(500)
		}
		res.send('ok')
	})
})
// 公交路线获取
router.use('/getBusRoutes',(req,res,next)=>{
	let id = req.query.car_id;
	
	connection.query(sql.bus.getBusRoutes,id,(err,result,fields)=>{
		if(err){
			console.log(err)
			res.status(500).send('error')
		}
		if(result.length == 0){
			res.send('no')
		}else{
			res.send(result)
		}
	})
})
// 公交路线插入
router.use('/insertBusRoutes',(req,res,next)=>{
	let busInfo = req.body;
	let info = [busInfo.car_id,busInfo.departure,busInfo.destination,busInfo.way]
	
	connection.query(sql.bus.insertBusRoutes,info,(err,result,fields)=>{
		if(err){
			console.log(err)
			res.status(500).send('error')
		}
		res.send('ok')
	})
})
// 公交路线修改
router.use('/updateBusRoutes',(req,res,next)=>{
	let busInfo = req.body;
	let info = [busInfo.departure,busInfo.destination,busInfo.way,busInfo.car_id,]
	connection.query(sql.bus.updateBusRoutes,info,(err,result,fields)=>{
		if(err){
			console.log(err)
			res.status(500).send('error')
		}
		res.send('ok')
	})
})
module.exports = router;